package com.example.forum_system.controller;

import com.example.forum_system.common.AppVar;
import com.example.forum_system.common.Result;
import com.example.forum_system.common.ResultCode;
import com.example.forum_system.model.Article;
import com.example.forum_system.model.User;
import com.example.forum_system.model.VO.ArticleVO;
import com.example.forum_system.searchEngine.ISearchEngine;
import com.example.forum_system.searchEngine.SearchEngine;
import com.example.forum_system.service.IArticleService;
import com.example.forum_system.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.controller
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-12  23:38
 * @Version : 1.0
 * @Description : TODO
 */
@RestController
@Slf4j
@RequestMapping("/article")
public class ArticleController {
    private ISearchEngine searchEngine;
    @Autowired
    IArticleService articleService;





    /*------------------------------------普--通--方--法------------------------------------------------------------------
     * @Desc  : 添加文章
     * @Param : [request, article]
     * @Return: com.example.forum_system.common.Result
    **/
    @PostMapping("/addArticle")
    public Result addArticle(HttpServletRequest request, Article article){
        //1.参数检验
        if(StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())
                || article.getBoardId() == null){
            log.error("文章传入参数异常");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.得到当前登录用户对象
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppVar.SESSION_USER);
        //3.检查当前登录用户的状态
        if(user.getState() == 1){
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }
        //4.添加文章到数据库
        article.setUserId(user.getId());
        if(articleService.insertArticle(article) != 1){
            log.error("文章插入数据库失败");
            return Result.failed(ResultCode.FAILED_CREATE);
        }
        //5.返回结果给前端
        return Result.success();
    }

    @GetMapping("/getAllArticle")
    public Result getAllArticleList(){
        List<ArticleVO> articleList = articleService.selectAllArticle();
        contentTailor(articleList);
        return Result.success(articleList);
    }

    @PostMapping("/getBoardArticle")
    public Result getBoardArticleList(Long boardId){
        if(boardId==null || boardId<0){
            log.warn("获取板块文章数时，传入板块id无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        List<ArticleVO> articleList = articleService.selectArticleBoard(boardId);
        contentTailor(articleList);
        return Result.success(articleList);
    }
    @RequestMapping("/getUserArticle")
    public Result getUserArticleList(HttpServletRequest request,Long userId){
        if(userId==null){
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppVar.SESSION_USER);
            userId = user.getId();
        }
        List<ArticleVO> articleList = articleService.selectArticleUser(userId);
        contentTailor(articleList);
        return Result.success(articleList);
    }

    @PostMapping("/getDetail")
    public Result getDetail(Long articleId){
        if(articleId==null || articleId<0){
            log.warn("获取板块文章数时，传入文章id无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        return Result.success(articleService.selectOneArticle(articleId));
    }
    
    @PostMapping("/delete")
    public Result deleteArticle(Long articleId){
        if(articleId==null || articleId<0){
            log.warn("删除文章数时，传入文章id无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        return Result.success(articleService.deleteArticle(articleId));
    }
    
    @PostMapping("/update")
    public Result updateAticle(HttpServletRequest request,Article article){
        //1.参数检验
        if(StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())
                || article.getId() == null){
            log.error("文章传入参数异常");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.得到当前登录用户对象
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppVar.SESSION_USER);
        //3.检查当前登录用户的状态
        if(user.getState() == 1){
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }
        //4.修改数据库中的文章
        article.setUserId(user.getId());
        if(articleService.updateArticle(article) != 1){
            log.error("文章修改失败");
            return Result.failed(ResultCode.FAILED);
        }
        //5.返回结果给前端
        return Result.success();
    }
    
    @PostMapping("/addLike")
    public Result addLike(Long articleId){
        if(articleId==null || articleId<0){
            log.warn("点赞时，传入文章id无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if(articleService.addLike(articleId) != 1){
            log.error("点赞失败");
            return Result.failed(ResultCode.FAILED);
        }
        return Result.success();
    }
    
    @PostMapping("/addVisit")
    public Result addVisit(Long articleId){
        if(articleId==null || articleId<0){
            log.warn("增加访问量时，传入文章id无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if(articleService.addVisit(articleId) != 1){
            log.error("增加访问量失败");
            return Result.failed(ResultCode.FAILED);
        }
        return Result.success();
    }

    @GetMapping("/search")
    public Result search(String search) throws Exception {
        //1.参数检验
        if(StringUtil.isEmpty(search)){
            log.warn("搜索时，传入参数无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.加载搜索引擎
        if(searchEngine == null){
            searchEngineStart();
        }
        //3.定义返回的博客列表
        List<ArticleVO> ret = new ArrayList<>();
        //4.搜索，得到符合要求博客的id列表
        List<Integer> list = searchEngine.search(search);
        if(list.size() == 0){
            return Result.success();
        }
        //5.根据得到的id列表加载博客列表
        for(long id:list){
            ret.add(articleService.selectOneArticle(id));
        }
        //6.返回列表给前端
        return Result.success(ret);
    }

    private void contentTailor(List<ArticleVO> articleList){
        for(Article article:articleList){
            if(article.getContent().length()>AppVar.CONTENT_TAILOR) {
                article.setContent(article.getContent().substring(0, AppVar.CONTENT_TAILOR));
            }
        }
    }

    private int searchEngineStart(){
        searchEngine = new SearchEngine();
        List<ArticleVO> articleList = articleService.selectAllArticle();
        for(Article article:articleList){
            int id = article.getId().intValue();
            String title = article.getTitle();
            String content = article.getContent();
            searchEngine.addArticle(title+content,id);
        }
        return articleList.size();
    }

}
